package com.agent.vpsserver.modules.admin.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
import com.agent.vpsserver.common.dto.AdminAccountTokenDTO;
import com.agent.vpsserver.common.dto.AdminUserCacheDTO;
import com.agent.vpsserver.common.exception.HintException;
import com.agent.vpsserver.common.utils.common.IdUtils;
import com.agent.vpsserver.common.utils.sign.Md5Utils;
import com.agent.vpsserver.modules.admin.entity.pojo.AdminUserDO;
import com.agent.vpsserver.modules.admin.mapper.AdminUserMapper;
import com.agent.vpsserver.modules.admin.request.AdminUserIoginRequest;
import com.agent.vpsserver.modules.admin.response.AdminUserInfoResponse;
import com.agent.vpsserver.modules.admin.service.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 用户信息(AdminUser)表服务实现类
 *
 * @author guochao
 * @since 2022-11-01 19:08:37
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUserDO> implements AdminUserService {

    private Cache<String, AdminUserCacheDTO> cache = new TimedCache<>(1000 * 60 * 60 * 6);

    @Override
    public AdminUserCacheDTO get(String token) {
        return cache.get(token);
    }

    @Override
    public AdminUserInfoResponse login(AdminUserIoginRequest request) {
        AdminUserDO adminUserDO = baseMapper.selectOne(new LambdaQueryWrapper<AdminUserDO>()
                .eq(AdminUserDO::getMobile, request.getMobile()));
        if (adminUserDO == null || adminUserDO.getStatus().equals(2)) {
            throw new HintException("手机号不存在");
        }
        if (adminUserDO.getStatus().equals(0)) {
            throw new HintException("用户已禁用");
        }
        String salt = adminUserDO.getSalt();
        String saltPwd = Md5Utils.saltPassword(request.getPassword(), salt);
        if (!saltPwd.equals(adminUserDO.getPassword())) {
            throw new HintException("密码错误");
        }
        // 缓存
        String token = IdUtils.uuid();
        AdminUserCacheDTO adminUserCacheDTO = new AdminUserCacheDTO();
        adminUserCacheDTO.setUserId(adminUserDO.getId());
        adminUserCacheDTO.setEmail(adminUserDO.getEmail());
        adminUserCacheDTO.setToken(token);
        adminUserCacheDTO.setMobile(adminUserDO.getMobile());
        adminUserCacheDTO.setUsername(adminUserDO.getUsername());
        adminUserCacheDTO.setRemark(adminUserDO.getRemark());
        cache.put(token, adminUserCacheDTO);

        AdminUserInfoResponse response = new AdminUserInfoResponse();
        response.setEmail(adminUserDO.getEmail());
        response.setMobile(adminUserDO.getMobile());
        response.setToken(token);
        response.setUsername(adminUserDO.getUsername());
        return response;
    }

    @Override
    public void logout(AdminAccountTokenDTO request) {
    }
}
